#!/usr/bin/perl -w
use strict;
### this one will generate a range based conservation database
### you give it the lower and upper bound it should calculate
### for each itteration, and it will tell you the conservation
### tracks that meet that criteria.  For example
### btw it needs to be executed from the directory the phastcon
### files are in and they are named by chromsome chr1 chr2 chr3
### ../../phastConvert_danrer4_abbrev.pl 0.05 0.1 would say 
### we will consider a conservation track to begin at 0.1 but we
### will terminate the conservation scoring if it drops below 0.5
### so in this way we can round it up to 0.1 as the bottom.

### be sure to modify the output file based on your needs and the way it reading the file list
### these are supposed to parse phastcon data into a more compact form that is similar to the
### bed peaks used in other parts of the program.


### run it from inside the same directory as all the unziped phastcon files.
### it creates a file in the same directory
my $genomename = 'mm9';
my $databasename = '_placental';

if(scalar(@ARGV) < 2) { die "no args\n"; }
my $lowerbound = shift @ARGV;
my $upperbound = shift @ARGV;
chomp(my @filenames = `ls chr*`);
open(OFIL,">$genomename$databasename_$lowerbound-$upperbound.phast.txt");
foreach my $filename(@filenames) {
  open(FILE,"$filename") or die "no $filename\n";
  my $chrom = $filename;
  if($filename=~/^(chr.+)\.data/) { $chrom = $1; }
  #print "$chrom\n";  
  my $location = 1;
  my $inrun = 0;
  while(<FILE>) { # read through the whole file
    chomp(my $line = $_);
    if($line =~ /start=(\d+)\s/) { $location = $1; }
    else {
      my $phastcon = $line;
      if($phastcon >= $upperbound && $inrun==0) { 
        $inrun = 1;
        print OFIL "$chrom\t$location\t"; 
      } elsif($phastcon < $lowerbound && $inrun==1) {
        print OFIL "$location\n"; #terminator
        $inrun = 0;
      }
      $location++;
    }
  }
  if($inrun==1) { print OFIL "$location\n"; }
  close FILE;
}
close OFIL;

